package Homework;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/*拷贝一个文件夹，包含子文件夹*/
public class work04 {
    public static void main(String[] args) {
        String oldPath = "d:\\Homework";
        String newPath = "d:\\newHomework";
        File dirNew = new File(newPath);
        dirNew.mkdirs();// 如果不存在则创建目录
        try{
            directory(oldPath,newPath);
            System.out.println("文件复制成功");
        }catch(Exception e){
            System.out.println("文件复制失败"+e.getMessage());
            e.printStackTrace();
        }
    }
    //复制单个文件
    private static void copyfile(String oldPath, String newPath) throws Exception {
        FileInputStream fis = new FileInputStream(oldPath);
        FileOutputStream fos = new FileOutputStream(newPath);
        byte[] buffer = new byte[1024];
        int ch;
        while((ch = fis.read(buffer)) != -1){
            fos.write(buffer,0,ch);
        }
    }
    //复制文件夹
    private static void directory(String oldPath, String newPath) throws Exception {
        // TODO Auto-generated method stub
        File oldFolder = new File(oldPath);
        File[] files = oldFolder.listFiles();
        if(files != null){
            for(File file : files){
                if(file.isDirectory()){
                    File newFolder = new File(newPath,file.getName());
                    newFolder.mkdirs();// 如果不存在则创建目录
                    directory(file.getAbsolutePath(), newFolder.getAbsolutePath());
                }else{
                    copyfile(file.getAbsolutePath(),newPath+File.separator+file.getName());
                }
            }
        }
    }
}
